package com.snow.useviewdemo.html;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

/**
 * Created by zyt on 2018/1/25.
 * 集成腾讯的TBS浏览器webview
 */

public class TBSWebView extends WebView {
    private ProgressBar progressbar;  //进度条
    private int progressHeight = 5;  //进度条的高度，默认10px
    private Context mContext;
    private boolean isShowProgressbar = true;//是否显示进度条

    public TBSWebView(Context context) {
        super(context);
        this.mContext = context;
        initView(context);
    }

    public TBSWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        this.mContext = context;
        initView(context);
    }

    private void initView(Context context) {
        startTime = System.currentTimeMillis();

        //开启js脚本支持
        WebSettings settings = getSettings();
        settings.setJavaScriptEnabled(true);

        //创建进度条
        progressbar = new ProgressBar(context, null,
                android.R.attr.progressBarStyleHorizontal);
        //设置加载进度条的高度
        progressbar.setLayoutParams(new AbsoluteLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, progressHeight, 0, 0));

//        Drawable drawable = context.getResources().getDrawable(R.drawable.webview_progress_drawable);
//        progressbar.setProgressDrawable(drawable);

        //添加进度到WebView
        addView(progressbar);
        settings.setUserAgentString(settings.getUserAgentString() + ";msgt_android");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //自动播放音视频
        settings.setMediaPlaybackRequiresUserGesture(false);
        //适配手机大小
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setGeolocationEnabled(true);
        String dir = context.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setGeolocationDatabasePath(dir);
        // enable Web Storage: localStorage, sessionStorage
        settings.setDomStorageEnabled(true);
        // 设置 缓存模式
//        s.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 设置 缓存模式
        settings.setAppCacheMaxSize(1024 * 1024 * 15);// 设置缓冲大小，我设的是15M
        String cacheDirPath = context.getFilesDir().getAbsolutePath() + "cache/";
        settings.setAppCachePath(cacheDirPath);
        // 开启 Application Caches 功能
        settings.setAppCacheEnabled(true);
        // 设置 Application Caches 缓存目录
        settings.setAppCachePath(cacheDirPath);
        settings.setAllowFileAccess(true);
        // 触摸焦点起作用
        requestFocus();
        setWebChromeClient(new WVChromeClient());
        setWebViewClient(new WVClient());

        setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                        long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                mContext.startActivity(intent);
            }
        });

    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (mScrollInterface != null) {
            mScrollInterface.onSChanged(l, t, oldl, oldt);
        }
    }

    private WebViewScrollInterface mScrollInterface;

    //供外部调用，监控滑动
    public void setOnCustomScrollChangeListener(WebViewScrollInterface scrollInterface) {
        this.mScrollInterface = scrollInterface;
    }

    public interface WebViewScrollInterface {
        void onSChanged(int l, int t, int oldl, int oldt);
    }

    @Override
    public void loadUrl(String s) {
        if (TextUtils.isEmpty(s)) {
            return;
        }
        //设置cookie
//        SystemUtils.synCookies(AppApplication.getInstance(), s);
        super.loadUrl(s);
    }

    /**
     * 是否显示进度条===默认显示
     *
     * @param flagBar
     */
    public void isShowProgressBar(boolean flagBar) {
        this.isShowProgressbar = flagBar;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (canGoBack()) {
                goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //进度显示
    private class WVChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (isShowProgressbar) {
                if (newProgress == 100) {
                    progressbar.setVisibility(GONE);
                } else {
                    if (progressbar.getVisibility() == GONE)
                        progressbar.setVisibility(VISIBLE);
                    progressbar.setProgress(newProgress);
                }
            } else {
                progressbar.setVisibility(GONE);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView webView, String s) {
            super.onReceivedTitle(webView, s);
            if (mListener != null) {
                mListener.onReceivedTitle(s);
            }
        }

        /*** 视频播放相关的方法 开始====================================== **/
        @Override
        public View getVideoLoadingProgressView() {
            FrameLayout frameLayout = new FrameLayout(mContext);
            frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            return frameLayout;
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            showCustomView(view, callback);
        }

        @Override
        public void onHideCustomView() {
            hideCustomView();
        }
    }

    private View customView;
    /**
     * 视频全屏参数
     */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private FrameLayout fullscreenContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;

    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }
        if (mContext == null) {
            return;
        }
        ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        Window window = ((Activity) mContext).getWindow();
        FrameLayout decor = (FrameLayout) window.getDecorView();
        fullscreenContainer = new FullscreenHolder(mContext);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */
    public void hideCustomView() {
        if (customView == null || mContext == null) {
            return;
        }
        ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setStatusBarVisibility(true);
        Window window = ((Activity) mContext).getWindow();
        FrameLayout decor = (FrameLayout) window.getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
    }

    /**
     * 全屏容器界面
     */
    static class FullscreenHolder extends FrameLayout {
        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        Window window = ((Activity) mContext).getWindow();
        window.setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    /*** 视频播放相关的方法 结束====================================== **/
    private long startTime;

    private class WVClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);
            if (mListener != null) {
                mListener.onStart();
            }
//            ToastUtils.getInstance().showToast("耗时=" + (System.currentTimeMillis() - startTime));
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            LogUtil.e("shouldOverrideUrlLoading===" + url);
            //这里需要写成false，true会导致h5中的二级界面可能无法跳转
            return false;
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
            return super.shouldInterceptRequest(webView, webResourceRequest);
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
            //https忽略证书问题
            sslErrorHandler.proceed();
            super.onReceivedSslError(webView, sslErrorHandler, sslError);
        }

        @Override
        public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
            super.onReceivedError(webView, webResourceRequest, webResourceError);
            if (mListener != null) {
                mListener.onLoadError();
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
//            LogUtil.e("onPageFinished===" + url);
//            ToastUtils.getInstance().showToast("耗时=" + (System.currentTimeMillis() - startTime));
            progressbar.setVisibility(GONE);
            if (mListener != null) {
                mListener.onPageFinish(view);
            }
            super.onPageFinished(view, url);

        }

    }

    private OnWebViewListener mListener;

    public void setOnWebViewListener(OnWebViewListener listener) {
        this.mListener = listener;
    }

    //进度回调接口
    public interface OnWebViewListener {
        void onStart();

        void onLoadError();

        void onPageFinish(WebView view);

        void onReceivedTitle(String title);
    }


    private void removeCookie(Context context) {

        CookieSyncManager.createInstance(context);

        CookieManager cookieManager = CookieManager.getInstance();

        cookieManager.removeAllCookie();

        CookieSyncManager.getInstance().sync();

    }

}
